#include <iostream>
using namespace std;
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>

#define BUFFER_SIZE 16
int main()
{   
    const char * filename = "./text.txt";

    int fd = open(filename,O_RDWR);
    if(fd == -1)
    {
        perror("open error:");
        exit(-1);
    }

    int length = lseek(fd,0,SEEK_END);
    printf("length = %d\n",length);

    void *addr =  mmap(NULL,length,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
    if(addr == MAP_FAILED)
    {
        perror("mmap error:");
        exit(-1);
    }

    close(fd);

    pid_t pid = fork();
    if(pid > 0)
    {
        printf("parent process.\n");

        const char *str = "hello world";


        strncpy((char*)addr,str,strlen(str)+1);
    }
    else if(pid == 0)
    {
        printf("child process.\n");

        usleep(1000);
        char buffer[BUFFER_SIZE] = {0};
        memcpy(buffer,addr,sizeof(buffer));
        printf("buffer = %s\n",buffer);
    }
    else
    {
        perror("fork error:");
        exit(-1);
    }

    munmap(addr,length);
    
    return 0;
}